package bootstrap

import (
	"go-fiber-demo/models"
	"go-fiber-demo/pkg"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
	"os"
	"time"
)

func InitDb(dbConfig pkg.DbConfig) *gorm.DB {
	dsn := dbConfig.Username + ":" + dbConfig.Password +
		"@tcp(" + dbConfig.Host + ":" + dbConfig.Port + ")" +
		"/" + dbConfig.Database + "?charset=" + dbConfig.Charset +
		"&parseTime=True&loc=" + dbConfig.Location

	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold: time.Millisecond * 50, // 慢 SQL 阈值
			LogLevel:      logger.Info,           // Log level
			Colorful:      true,                  // 禁用彩色打印
		},
	)

	db, err := gorm.Open(mysql.New(mysql.Config{
		DSN: dsn,
		//DontSupportRenameIndex:  true,
		//DontSupportRenameColumn: true,
		DefaultStringSize: 191,
	}), &gorm.Config{
		Logger:                                   newLogger,
		DisableForeignKeyConstraintWhenMigrating: true,
	})
	if err != nil {
		panic(err.Error())
	}

	pkg.GetConfig().GormDb = db
	return db
}

func AutoMergeModel(db *gorm.DB) {
	_ = db.AutoMigrate(&models.User{})
}
